package com.efounder.chat.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

import com.efounder.chat.event.LiveVideoSysEvent;
import com.efounder.chat.event.MeetingSysEvent;
import com.efounder.chat.manager.SystemMessageHandleManager;
import com.efounder.chat.model.ChatListItem;
import com.efounder.chat.model.NoticeMessageEvent;
import com.efounder.chat.model.TaskRefreshEvent;
import com.efounder.chat.model.UpdateResEvent;
import com.efounder.chat.utils.AppUtils;
import com.efounder.chat.utils.ChatListHelper;
import com.efounder.chat.utils.GroupAvatarHelper;
import com.efounder.chat.utils.HandleReceiveCommonMessageUtil;
import com.efounder.chat.utils.IMStruct002Util;
import com.efounder.chat.utils.ImNotificationUtil;
import com.efounder.chat.utils.JFChatStyleManager;
import com.efounder.chat.utils.RingVibratorUtils;
import com.efounder.chat.utils.ServiceUtils;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.form.application.util.FormAppUtil;
import com.efounder.frame.manager.AppAccountResDownloader;
import com.efounder.frame.utils.Constants;
import com.efounder.frame.utils.EFAppAccountFormUtils;
import com.efounder.frame.utils.EFAppAccountUtils;
import com.efounder.interfaces.BadgeUtil;
import com.efounder.message.manager.JFMessageListener;
import com.efounder.message.manager.JFMessageManager;
import com.efounder.message.struct.IMStruct002;
import com.efounder.util.EnvSupportManager;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

import javax.xml.parsers.DocumentBuilderFactory;

import static com.efounder.chat.struct.MessageChildTypeConstant.live_System_Msg;
import static com.efounder.chat.struct.MessageChildTypeConstant.meeting_System_Msg;
import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_App;
import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_AppRes;
import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_masterdata;
import static com.efounder.chat.struct.MessageChildTypeConstant.subtype_officalAccountRes;
import static com.efounder.frame.utils.Constants.CHAT_USER_ID;


//import com.efounder.deviceadmin.DeviceInfoManager;
//import com.efounder.deviceadmin.PansoftDeviceAdminManager;
//import com.efounder.deviceadmin.PansoftDeviceAdminReceiver;

/**
 * 系统消息监听服务
 */
public class SystemInfoService extends Service {
    private static final String TAG = "SystemInfoService";
    private static final String TYPE_GROUPAPPLY = "TYPE_GROUPAPPLY";//加群申请，
    private static final String TYPE_FRIENDAPPLY = "TYPE_FRIENDAPPLY";//好友申请

    //用来记录是否需要请求群组成员数据的map，例如群组id是123，如果map中包含此id，就不再请求该群组的人员信息
    public static volatile Map<Integer, Boolean> CHATMAP = new ConcurrentHashMap<>();
    //置顶计数 ----不要用 volatile 修饰
//    public static volatile int TOPINDEX = -1;

    //聊天列表以及聊天列表的map
    public static volatile List<ChatListItem> CHATITEMLIST = Collections.synchronizedList(new ArrayList<ChatListItem>());
    //    public static volatile Map<String, ChatListItem> CHATLISTMAP = Collections.synchronizedMap(new HashMap<String, ChatListItem>());
    public static volatile Map<String, ChatListItem> CHATLISTMAP = new ConcurrentHashMap<>();
    private ChatListHelper chatListHelper;

    /**
     * 消息管理器
     **/
    private JFMessageManager messageManager;
    /**
     * 消息监听
     **/
    private JFMessageListener messageListener;


    /**
     * 群组头像生成
     */
    private GroupAvatarHelper helper;
    //系统消息处理类
    private SystemMessageHandleManager systemMessageHandleManager;
    //是否支持IM消息服务
    private boolean supportIM = true;

    private ForegroundServiceDelegate foregroundServiceDelegate;


    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "---onCreate---");
        foregroundServiceDelegate = new ForegroundServiceDelegate(this);
        supportIM = EnvSupportManager.isSupportIM();
        if (!supportIM) {
            return;
        }
        foregroundServiceDelegate.startForeground();

//        chatListHelper = new ChatListHelper(getApplicationContext());
//        chatListHelper.initData();

        if (!ServiceUtils.isServiceRunning(getApplicationContext(), MessageService.class
                .getCanonicalName())) {
            try {
                startService(new Intent(getApplicationContext(), MessageService.class));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            messageListener = new ChatMessageListener();
            systemMessageHandleManager = new SystemMessageHandleManager(this);
//            WeChatDBManager.getInstance() = WeChatDBManager.getInstance();
//            helper = new GroupAvatarHelper(getApplicationContext());
        } catch (Exception e) {
            e.printStackTrace();
        }
        BadgeUtil.initTotal();
        me.leolin.shortcutbadger.ShortcutBadger.applyCount(getApplicationContext(), BadgeUtil.getTotalUnReadNum());
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "---onCreate---");

        if (!supportIM) {
            return super.onStartCommand(intent, flags, startId);
        }
        try {
            chatListHelper = ChatListHelper.getInstance(getApplicationContext());
            chatListHelper.initData();
            // messageListener = new ChatMessageListener();
            helper = new GroupAvatarHelper(getApplicationContext());

            messageManager = JFMessageManager.getInstance();
            messageManager.removeMessageListener(TAG, messageListener);
            messageManager.addMessageListener(TAG, messageListener);
//            systemMessageHandleManager.setWeChatDBManager.getInstance()(WeChatDBManager.getInstance());
            systemMessageHandleManager.setHelper(helper);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return START_STICKY;
    }

    /**
     * 回话界面各种消息状态的监听
     */
    private class ChatMessageListener implements JFMessageListener {

        @Override
        public synchronized void onReceive(IMStruct002 imstruct002) {

            Log.i(TAG, TAG + "服务正在运行--------");
            if (imstruct002.getMessageChildType() >= 100 && imstruct002.getMessageChildType() < 200) {//系统消息区间
                systemMessageHandleManager.dealSystemMessage(imstruct002);
            } else if (imstruct002.getMessageChildType() >= 200 && imstruct002.getMessageChildType() < 250) {//应用号表单自定义脚本消息区间
                dealScriptMessage(imstruct002);
            } else if (imstruct002.getMessageChildType() == subtype_masterdata) {
                try {
                    String jsons = new String(imstruct002.getBody(), "UTF-8");
                    //主数据存储到本地文件  appAccountID 要从imstruct002中获取
                    EFAppAccountFormUtils.saveMainData(jsons, imstruct002.getFromUserId());
                    //FileUtils.writeTextFile(EFAppAccountUtils.getAppAccountJsonPath() + "/" + "master_data.json", jsons);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else if (imstruct002.getMessageChildType() == subtype_officalAccountRes) {
                //{"CMD":"updateAppAccountRes","version":"0.0.3","updateNote":"1.应用号资源更新","isUpdate":true}
                //1.判断是否需要升级
                if (AppAccountResDownloader.isNeedUpdate(imstruct002)) {
                    //应用号资源更新发送广播 yqs
                    Intent intent = new Intent();
                    intent.putExtra("num", "1");
                    intent.putExtra("id", imstruct002.getFromUserId());
                    intent.putExtra("type", "appaccountres");
                    intent.setAction("com.efounder.updateres");
                    getApplicationContext().sendBroadcast(intent);
                }
            } else if (imstruct002.getMessageChildType() == subtype_App) {
                //todo APP版本更新发送广播
                try {
                    UpdateResEvent event = new UpdateResEvent();
                    String json = new String(imstruct002.getBody(), "UTF-8");
                    JSONObject jsonObject = new JSONObject(json);

                    event.setId(imstruct002.getFromUserId());
                    event.setVersion(jsonObject.getString("version"));//版本号
                    event.setUpdateNote(jsonObject.getString("updateNote"));//更新说明
                    event.setType(UpdateResEvent.TYPE_APP_UPDATE);
                    event.setUrl(jsonObject.getString("url"));
                    EventBus.getDefault().post(event);
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else if (imstruct002.getMessageChildType() == subtype_AppRes) {
                //todo APP资源文件更新发送广播 yqs
                try {
                    String json = new String(imstruct002.getBody(), "UTF-8");
                    JSONObject jsonObject = new JSONObject(json);
                    UpdateResEvent event = new UpdateResEvent();

                    event.setId(imstruct002.getFromUserId());
                    event.setVersion(jsonObject.getString("version"));//版本号
                    event.setUpdateNote(jsonObject.getString("updateNote"));//更新说明
                    event.setType(UpdateResEvent.TYPE_APP_RES_UPDATE);
                    event.setUrl("");
                    EventBus.getDefault().post(event);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (imstruct002.getMessageChildType() == live_System_Msg) {//直播点播类型
                EventBus.getDefault().post(new LiveVideoSysEvent(imstruct002));
            } else if (imstruct002.getMessageChildType() == meeting_System_Msg) {//会议消息
                EventBus.getDefault().post(new MeetingSysEvent(imstruct002));
            } else if (imstruct002.getMessageChildType() < 100) {
                //todo 处理聊天气泡 头像
                JFChatStyleManager.prepareMessage(imstruct002);
                //todo 处理积分相关消息
                //JFChatIntegralManager.handleInTegralMessage(imstruct002,true);
                //震动，声音
                RingVibratorUtils.RingingAndVibrate(getApplicationContext(), imstruct002);

                //处理收到的普通消息
                HandleReceiveCommonMessageUtil.handleMessage(imstruct002);

                chatListHelper.createOrUpdateChatListItem(imstruct002);

                int userId = 0;
                if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileLiveAppTGTest")) {
                    userId = 709;
                } else if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("OSPMobileLiveAppTG")) {
                    userId = 6392;
                } else if (EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobileYS") || EnvironmentVariable.getProperty(Constants.KEY_SETTING_APPID).equals("ZSYGXOSPMobile")) {
                    userId = 2299;
                }
                if (imstruct002.getFromUserId() == userId) {//// TODO: 17-8-3 铁工测试709，正式6392,财务共享2299
                    //任务中心公众号，收到后刷新任务界面，并给RN传递参数
                    EventBus.getDefault().post(new TaskRefreshEvent(imstruct002));
                }

                Log.i(TAG, "--=--imstruct002---" + imstruct002.getMessage());
                boolean isApplicationToBackground = AppUtils.isApplicationToBackground(getApplicationContext());
                Log.i(TAG, "---application is background:" + isApplicationToBackground);
                if (isApplicationToBackground) {
                    Log.i(TAG, "----line156---");
                    if (imstruct002.getFromUserId() != Integer.valueOf(EnvironmentVariable.getProperty(CHAT_USER_ID))) {
                        Log.i(TAG, "---line159---" + imstruct002.getFromUserId() + "," + EnvironmentVariable.getProperty(CHAT_USER_ID));
                        ImNotificationUtil.showNotificationIm(getApplicationContext(), imstruct002);

                    }
                }

                if (BadgeUtil.getTotalUnReadNum() == -1) {
                    BadgeUtil.initTotal();
                } else {
                    BadgeUtil.totalUnReadNum++;
                }
                //   me.leolin.shortcutbadger.ShortcutBadger.applyCount(getApplicationContext(), BadgeUtil.getTotalUnReadNum());

            }

        }

        @Override
        public synchronized void onUpdate(int i, IMStruct002 imstruct002) {
            Log.i(TAG, "onUpdate------消息状态：" + imstruct002.getState());
            if (imstruct002.getState() <= IMStruct002.MESSAGE_STATE_PRESEND) {
                //处理聊天气泡 头像
                JFChatStyleManager.prepareMessage(imstruct002);
            }
            //处理积分相关消息
            //JFChatIntegralManager.handleInTegralMessage(imstruct002,false);

            if (imstruct002.getState() == IMStruct002.MESSAGE_STATE_READ
                    || imstruct002.getState() == IMStruct002.MESSAGE_STATE_RECEIVE
                    || imstruct002.getState() == IMStruct002.MESSAGE_STATE_UNREAD
                    || imstruct002.getState() == IMStruct002.MESSAGE_STATE_DELETE || IMStruct002Util.isSystemMessage(imstruct002)) {
                if (imstruct002.getState() == IMStruct002.MESSAGE_STATE_RECEIVE) {
                    EventBus.getDefault().post(new NoticeMessageEvent(imstruct002.getToUserId() + "", i + ""));
                }

            } else {
                if (imstruct002.getMessageChildType() < 100) {
                    chatListHelper.createOrUpdateChatListItem(imstruct002);
                }
            }

        }

        @Override
        public void onFailure(int i, IMStruct002 imstruct002) {
            Log.i(TAG, "onFailure------消息状态：" + imstruct002.getState());
        }
    }

    @Override
    public void onDestroy() {

        Log.i(TAG, TAG + "---------onDestroy");
        super.onDestroy();
        JFMessageManager.getInstance().removeMessageListener(TAG, messageListener);
        CHATMAP.clear();
        CHATITEMLIST.clear();
        CHATLISTMAP.clear();
        ChatListHelper.release();
        foregroundServiceDelegate.stopForeground(true);
    }

    /**
     * 处理脚本类型消息
     */
    private void dealScriptMessage(IMStruct002 imstruct002) {
        Node scripChildNode = findScriptNode(imstruct002);
        if (scripChildNode == null) {
            return;
        }
        //读取到脚本，并执行脚本
        String script = getScript(imstruct002, scripChildNode);
        //
        FormAppUtil.executeScript(script);
    }

    /***
     * 根据消息类型，找到对应得脚本节点
     *
     * @param imstruct002
     * @return
     */
    private Node findScriptNode(IMStruct002 imstruct002) {
        int fromUserId = imstruct002.getFromUserId();//应用号id
        String path = EFAppAccountUtils.getAppAccountAppsPath() + "/" + fromUserId + "/app_frame.xml";
        //读取 xml中配置的脚本
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(new File(path));
            Element rootElement = document.getDocumentElement();
            NodeList nodeList = rootElement.getElementsByTagName("scriptObject");
            if (nodeList == null || nodeList.getLength() == 0) {
                return null;
            }
            Node scriptNode = nodeList.item(0);
            if (scriptNode.getNodeType() == Node.ELEMENT_NODE) {
                Element scriptElement = (Element) scriptNode;
                NodeList scriptChildNodes = scriptElement.getChildNodes();
                for (int i = 0; i < scriptChildNodes.getLength(); i++) {
                    Node scripChildNode = scriptChildNodes.item(i);
                    if (scripChildNode.getNodeType() == Node.ELEMENT_NODE) {
                        String id = scripChildNode.getAttributes().getNamedItem("id").getNodeValue();
                        if (id.equals("message_type_" + imstruct002.getMessageChildType())) {
                            return scripChildNode;
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private String getScript(IMStruct002 imstruct002, Node scripChildNode) {
        String script = null;
        try {
            JSONObject jsonObject = new JSONObject(imstruct002.getMessage());
            script = scripChildNode.getTextContent();
            //解析参数
            String arguments = scripChildNode.getAttributes().getNamedItem("arguments").getNodeValue();
            if (arguments != null && arguments.length() > 0) {
                String[] argumentArray = arguments.split(";");
                for (String argument : argumentArray) {
                    String argumentValue = jsonObject.getString(argument);
                    script = script.replaceAll("@" + argument + "@", argumentValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return script;
    }

}
